<template>
  <div
    :style="{
      width: '100%',
      height: '100%',
    }"
  >
    <el-auto-resizer>
      <template #default="{ height, width }">
        <el-table-v2 :columns="columns" :data="tableData" :width="width" :height="height" fixed />
      </template>
    </el-auto-resizer>
  </div>
</template>

<script setup>
import { newsList } from '@/api'
import dayjs from 'dayjs'

const columns = ref([
  { dataKey: 'id', title: '#', key: 'id', width: 150 },
  { dataKey: 'title', title: '标题', key: 'title', width: 150 },
  {
    dataKey: 'image',
    title: '图片',
    key: 'image',
    width: 100,
    height: 50,
    cellRenderer: ({ cellData }) => {
      return h('div', { class: ['w-24', 'h-12'] }, h('img', { src: cellData, class: ['w-full', 'h-full', 'object-cover', 'object-center'] }))
    },
  },
  { dataKey: 'readnum', title: '阅读量', key: 'readnum', width: 150 },
  { dataKey: 'isHome', title: '推荐', key: 'isHome', width: 150 },
  {
    dataKey: 'created_at',
    title: '发布时间',
    key: 'created_at',
    width: 150,
    cellRenderer: ({ cellData }) => {
      return dayjs(cellData).format('YYYY.MM.DD HH:mm')
    },
  },
])
const SelectionCell = ({ value, intermediate = false, onChange }) => {
  return <Elcheckbox onChange={onChange} modelValue={value} inderterminate={intermediate} />
}
columns.value.unshift({
  dataKey: 'selection',
  title: '#',
  key: 'id',
  width: 50,
  cellRenderer: ({ rowData }) => {
    const onChange = value => (rowData.checked = value)
    return <SelectionCell value={rowData.checked} onChange={onChange} />
  },
})

const tableData = ref([])
const params = ref({
  page: 1,
  limit: 10,
})

onMounted(() => {
  // newsList({}).then(res => {
  //   console.info(res)
  // })
  useList(params.value)
})

const useList = async params => {
  const { code, data, msg } = await newsList(params)
  tableData.value = data.items
  // tableData.value.forEach(item => {
  //   item.created_at = dayjs(item.created_at).format('YYYY-MM-DD HH:mm')
  // })
}

const generateColumns = (length = 10, prefix = 'column-', props) =>
  Array.from({ length }).map((_, columnIndex) => ({
    ...props,
    key: `${prefix}${columnIndex}`,
    dataKey: `${prefix}${columnIndex}`,
    title: `Column ${columnIndex}`,
    width: 150,
  }))

const generateData = (columns, length = 200, prefix = 'row-') =>
  Array.from({ length }).map((_, rowIndex) => {
    return columns.reduce(
      (rowData, column, columnIndex) => {
        rowData[column.dataKey] = `Row ${rowIndex} - Col ${columnIndex}`
        return rowData
      },
      {
        id: `${prefix}${rowIndex}`,
        parentId: null,
      }
    )
  })

// const columns = generateColumns(10)
// const tableData = generateData(columns, 200)
// console.log('tableData: ', columns, tableData)
</script>
